package cn.lingyangwl.agile.infra.gen.service.impl;

import cn.lingyangwl.agile.infra.gen.mapper.GenerateHistoryMapper;
import cn.lingyangwl.agile.infra.gen.model.entity.GenerateHistory;
import cn.lingyangwl.agile.infra.gen.model.rqrs.GeneratorReq;
import cn.lingyangwl.agile.infra.gen.service.GenerateHistoryService;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author shenguangyang
 */
@Service
@RequiredArgsConstructor
public class GenerateHistoryServiceImpl implements GenerateHistoryService {
    private final GenerateHistoryMapper generateHistoryMapper;

    @Override
    @Transactional
    public void saveHistory(GeneratorReq req) {
        String content = JSON.toJSONString(req);
        String md5 = DigestUtils.md5DigestAsHex(content.getBytes(StandardCharsets.UTF_8));
        LambdaQueryWrapper<GenerateHistory> wrapper = Wrappers.<GenerateHistory>lambdaQuery()
                .eq(GenerateHistory::getMd5Value, md5);
        GenerateHistory history = generateHistoryMapper.selectOne(wrapper);
        if (history != null) {
            generateHistoryMapper.updateById(history);
            return;
        }
        GenerateHistory generateHistory = new GenerateHistory();
        generateHistory.setConfigContent(content);
        generateHistory.setMd5Value(md5);
        generateHistoryMapper.insert(generateHistory);
    }

    @Override
    public List<GenerateHistory> listAll() {
        return generateHistoryMapper.selectList(new LambdaQueryWrapper<>());
    }

    @Override
    public GenerateHistory getById(Long id) {
        return generateHistoryMapper.selectById(id);
    }

    @Override
    public void save(GenerateHistory generateHistory) {
        if (generateHistoryMapper.insert(generateHistory) <= 0) {
            throw new BizException("保存失败");
        }
    }

    @Override
    public void update(GenerateHistory generateHistory) {
        if (generateHistoryMapper.updateById(generateHistory) <= 0) {
            throw new BizException("更新失败");
        }
    }

    @Override
    public void delete(GenerateHistory generateHistory) {
        if (generateHistoryMapper.deleteById(generateHistory) <= 0) {
            throw new BizException("删除失败");
        }
    }


}
